package com.app.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.app.common.Weather;

public class XmlHelper {

	public Document getXml(List<Weather> list) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("weatherInfo");
		Iterator<Weather> iter = list.iterator();
		while (iter.hasNext()) {
			Weather weather = iter.next();
			weather.toXML(root);
		}
		String xml = document.asXML();
		System.out.println(xml);
		return document;
	}

	public TreeMap<String, String> read(HttpServletRequest request) {
		StringBuilder stringBuilder = new StringBuilder();
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
		String line = null;
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = request.getReader();
			while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line);
			}
			Document document = DocumentHelper.parseText(stringBuilder
					.toString());
			Element root = document.getRootElement();
			Iterator<Element> iter = root.elementIterator();
			while (iter.hasNext()) {
				Element element = iter.next();
				treeMap.put(element.getName(), element.getTextTrim());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null)
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return treeMap;
	}
}
